<template>
  <div class="chat-window-main" v-if="chatUser">
    <!-- 顶部：好友头像+昵称 -->
    <div class="chat-header">
      <img :src="chatUser.avatar || require('@/assets/default-avatar.png')" class="avatar" />
      <span class="nickname">{{ chatUser.nickname }}</span>
    </div>
    <!-- 聊天记录 -->
    <div class="chat-messages" ref="msgList">
      <div
        v-for="(msg, index) in messages"
        :key="msg.id || msg.createTime || index"
        :class="['msg-row', msg.fromId === userId ? 'my-msg' : 'other-msg']"
      >
        <img v-if="msg.fromId !== userId" :src="chatUser.avatar || require('@/assets/default-avatar.png')" class="msg-avatar" />
        <div class="msg-bubble">
          <span>{{ msg.content }}</span>
        </div>
        <img v-if="msg.fromId === userId" :src="myAvatar || require('@/assets/default-avatar.png')" class="msg-avatar" />
      </div>
    </div>
    <!-- 输入框 -->
    <div class="chat-input-bar">
      <input v-model="input" @keyup.enter="sendMsg" placeholder="请输入消息..." />
      <button @click="sendMsg">发送</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { connectWebSocket, onMessage, sendMessage } from '@/utils/ws'
// 移除 defaultAvatar 的 import

export default {
  props: { chatUser: Object },
  data() {
    return {
      userId: null,
      myAvatar: '',
      messages: [],
      input: ''
    }
  },
  watch: {
    chatUser: {
      immediate: true,
      handler() {
        this.loadMessages()
      }
    }
  },
  async mounted() {
    this.userId = Number(localStorage.getItem('userId'))
    // 获取当前用户头像
    const res = await axios.get('/api/user/info', { params: { userId: this.userId } })
    this.myAvatar = res.data.avatar
    connectWebSocket(this.userId)
    onMessage((msg) => {
      console.log('收到ws消息：', msg)
      // 类型转换，确保判断成立
      const fromId = Number(msg.fromId)
      const toId = Number(msg.toId)
      const chatId = Number(this.chatUser && this.chatUser.id)
      if (
        (fromId === chatId && toId === this.userId) ||
        (fromId === this.userId && toId === chatId)
      ) {
        this.messages.push(msg)
        this.$nextTick(this.scrollToBottom)
      }
    })
  },
  methods: {
    async loadMessages() {
      if (!this.chatUser) return
      const userId = Number(localStorage.getItem('userId'))
      const friendId = Number(this.chatUser.id)
      try {
        const res = await axios.get('/api/message/history', {
          params: { userId, friendId }
        })
        this.messages = res.data
        this.$nextTick(this.scrollToBottom)
      } catch (e) {
        this.messages = []
        console.error('获取聊天记录失败', e)
      }
    },
    sendMsg() {
      if (!this.input.trim()) return
      const msg = {
        fromId: this.userId,
        toId: Number(this.chatUser.id),
        content: this.input,
        // 可加时间戳等
      }
      sendMessage(msg)
      this.messages.push(msg) // 本地立即显示
      this.input = ''
      this.$nextTick(this.scrollToBottom)
    },
    scrollToBottom() {
      const el = this.$refs.msgList
      if (el) el.scrollTop = el.scrollHeight
    }
  }
}
</script>

<style scoped>
.chat-window-main { display: flex; flex-direction: column; height: 100%; }
.chat-header {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #eee;
  background: #f7f7f7;
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 10px;
}
.nickname {
  font-weight: bold;
  font-size: 18px;
}
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #e5ddd5; /* 微信聊天背景色 */
}
.msg-row {
  display: flex;
  align-items: flex-end;
  margin-bottom: 16px;
}
.my-msg {
  flex-direction: row-reverse;
}
.msg-avatar {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  margin: 0 8px;
}
.msg-bubble {
  max-width: 320px;
  padding: 10px 16px;
  border-radius: 8px;
  background: #fff;
  font-size: 15px;
  word-break: break-all;
  box-shadow: 0 1px 2px rgba(0,0,0,0.04);
}
.my-msg .msg-bubble {
  background: #95ec69; /* 微信绿色 */
  color: #222;
}
.other-msg .msg-bubble {
  background: #fff;
  color: #222;
}
.chat-input-bar {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  border-top: 1px solid #eee;
  background: #f7f7f7;
}
.chat-input-bar input {
  flex: 1;
  border: 1px solid #ccc;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 15px;
  outline: none;
}
.chat-input-bar button {
  margin-left: 12px;
  background: #07c160;
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 8px 24px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.chat-input-bar button:hover {
  background: #13ce66;
}
.session-list {
  width: 260px;
  background: #f5f5f5;
  border-right: 1px solid #e4e4e4;
  overflow-y: auto;
}
.session-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  transition: background 0.2s;
}
.session-item.active, .session-item:hover {
  background: #e1f3d8;
}
.session-avatar {
  width: 44px;
  height: 44px;
  border-radius: 8px;
  margin-right: 12px;
}
</style>